<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Http\Requests\Api\UserRequest;
use App\Transformers\UserTransformer;

class UsersController extends Controller
{
    public function store(UserRequest $request)
    {
        $verifyData = \Cache::get($request->verification_key);

        if (!$verifyData) {
            return $this->response->array([
                'status' => false,
                'data' =>[
                    'successflag' =>false
                ],
                'message' => '验证码已失效.',
            ])->setStatusCode(422);
        }

        if (!hash_equals($verifyData['code'], $request->verification_code)) {
            // 返回401
            return $this->response->array([
                'status' => false,
                'data' =>[
                    'successflag' =>false
                ],
                'message' => '验证码错误.',
            ])->setStatusCode(401);
        }

        $user=User::where('name', $verifyData['name'])->first();

        if (!$user) {
            $user = User::create([
                'name' => $verifyData['name'],
                'password' => bcrypt(str_random(10)),
            ]);
        }

        // 清除验证码缓存
        \Cache::forget($request->verification_key);

        $token = \Auth::guard('api')->fromUser($user);
        return $this->response->array([
            'status'=>true,
            'data'=>[
                'successflag' => true,
                'access_token' => $token,
                'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60,
            ],
            'message'=>'成功'
        ]);
    }

    public function me()
    {
        return $this->response->item($this->user(), new UserTransformer());
    }

    public function update(UserRequest $request)
    {
        $user = $this->user();
        $this->authorize('update', $user);

        $attributes = $request->only(['nickname', 'realname', 'phone', 'introduction', 'remark', 'avatar', 'address']);

        if (is_null($user)) {
            return $this->response->array([
                'status' => false,
                'data' =>[
                    'successflag' =>false
                ],
                'message' => '用户不存在.',
            ])->setStatusCode(400);
        }

        // dd($attributes);

        $user->update($attributes);

        return $this->response->item($user, new UserTransformer())->setStatusCode(201);;
    }
}
